package com.example.music_player_app.ui.playSong;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.Activity;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.music_player_app.Bean.SongDetail;
import com.example.music_player_app.R;
import com.example.music_player_app.utils.DBHelper;
import com.example.music_player_app.utils.MediaPlayerServer;
import com.example.music_player_app.view.MyImageView;

import java.io.IOException;

public class PlaySong extends AppCompatActivity implements View.OnClickListener{
    private ImageView perSong; //前一首
    private ImageView playSong; // 播放
    private ImageView stopSong; // 暂停
    private ImageView nextSong; // 下一首
    private SeekBar seekBar; // 进度条
    private SongDetail songDetail; // 歌曲详情
    private boolean isPause; // 是否暂停
    private SharedPreferences sp;
    private SharedPreferences.Editor ed;

    private DBHelper dbHelper;
    private SQLiteDatabase db;
    private Cursor cursor;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_song);

        perSong = findViewById(R.id.per_song);
        playSong = findViewById(R.id.play_song);
        stopSong = findViewById(R.id.stop_song);
        nextSong = findViewById(R.id.next_song);

        perSong.setOnClickListener(this);
        playSong.setOnClickListener(this);
        stopSong.setOnClickListener(this);
        nextSong.setOnClickListener(this);

        seekBar = findViewById(R.id.song_seek_bar);

        toolbar = findViewById(R.id.play_tool_bar);
        toolbar.setTitle("正在播放");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);


        sp = getSharedPreferences("base_settings", Activity.MODE_PRIVATE);

        dbHelper = new DBHelper(this, "musicPlayerDB.db", null, 1);
        db = dbHelper.getWritableDatabase();

        initPlayDetail(); // 初始化播放歌曲信息

        initAutoPlay(); //自动切歌

    }

    private void initAutoPlay() {
        MediaPlayerServer.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                System.out.println("播放完成");
                handler.removeCallbacks(updateThread);
                try {
                    playNextSong(songDetail.getId());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initPerAndNext(long id) {
        TextView textView2 = findViewById(R.id.textView2);
        TextView textView = findViewById(R.id.textView3);
        String sql = "select * from myMusic where id>" + id + " limit 1";
        cursor = db.rawQuery(sql, null);
        if(cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                String name = cursor.getString(cursor.getColumnIndex("name"));
                textView.setText("下一首："+name);
            }
        }else {
            textView.setText("下一首：暂无歌曲");
        }

        sql = "select * from myMusic where id<" + id + " order by id DESC limit 1 ";
        cursor = db.rawQuery(sql, null);
        if(cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                String name = cursor.getString(cursor.getColumnIndex("name"));
                textView2.setText("上一首："+name);
            }
        }else {
            textView2.setText("上一首：暂无歌曲");
        }
    }

    Handler handler = new Handler(Looper.getMainLooper());
    Runnable updateThread = new Runnable() {
        public void run() {
            //获得歌曲现在播放位置并设置成播放进度条的值
            seekBar.setProgress(MediaPlayerServer.mediaPlayer.getCurrentPosition());
            //每次延迟 100 毫秒再启动线程
            handler.postDelayed(updateThread, 100);
        }
    };

    private void initPlayDetail() {
        Bundle bundle = this.getIntent().getExtras();
        Boolean isClickPlay = bundle.getBoolean("isClickPlay"); // 是否通过点击播放歌曲进入此页面
        if(isClickPlay) {
            // 判断当前是否正在播放，有的话暂停并重置播放器
            if(sp.getBoolean("isPlaying", false)) {
                MediaPlayerServer.mediaPlayer.release();
            }
            songDetail = (SongDetail) bundle.getSerializable("song_detail");
            if(songDetail.getPlayUrl() == null) {
                Toast.makeText(this,"歌曲暂时没有播放资源",Toast.LENGTH_SHORT).show();
                return;
            }
            if(songDetail != null) {
                TextView textView = findViewById(R.id.play_song_name);
                MyImageView imageView = findViewById(R.id.play_song_img);

                textView.setText(songDetail.getName());
                imageView.setImageURL(songDetail.getSongImgUrl());

                playSong(songDetail.getPlayUrl());

            }
            initPerAndNext(songDetail.getId()); // 初始化上一首下一首
        }else {
            return;
        }
    }

    // 设置播放器
    private void playSong(String playUrl) {
        playUrl = playUrl.replace("http", "https");
        MediaPlayerServer.mediaPlayer = MediaPlayer.create(this, Uri.parse(playUrl));
        seekBar.setMax(MediaPlayerServer.mediaPlayer.getDuration());
        playSong.performClick();
    }

    // 播放音乐
    private void initPlay(String playUrl) {
        try {
            if(isPause) {
                MediaPlayerServer.mediaPlayer.start();
                isPause = false;
            } else {
                // 设备初始化
                MediaPlayerServer.mediaPlayer.reset();
                // 设置数据源
                MediaPlayerServer.mediaPlayer.setDataSource(playUrl);
                // prepare 之后自动播放
                MediaPlayerServer.mediaPlayer.prepare();
                MediaPlayerServer.mediaPlayer.start();
                isPause = false;
            }

            ed = sp.edit();
            ed.putBoolean("isPlaying", true); // 是否有音乐正在播放
            ed.apply();

        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.per_song:
                // TODO 前一首
                handler.removeCallbacks(updateThread);
                try {
                    playPreSong(songDetail.getId());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("前一首");
                break;
            case R.id.play_song:
                initPlay(songDetail.getPlayUrl());
                handler.post(updateThread);
                System.out.println("播放");
                break;
            case R.id.stop_song:
                MediaPlayerServer.mediaPlayer.pause();
                isPause = true; // 设置为暂停
                handler.post(updateThread);
                System.out.println("暂停");
                break;
            case R.id.next_song:
//                 TODO 下一首
                handler.removeCallbacks(updateThread);
                try {
                    playNextSong(songDetail.getId());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("下一首");
                break;
            case R.id.song_seek_bar:
                seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        // fromUser 判断是用户改变的滑块的值
                        if (fromUser) {
                            System.out.println("滑动了");
                            MediaPlayerServer.mediaPlayer.seekTo(progress);
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {

                    }
                });
        }
    }

    // 播放下一首
    private void playNextSong(long id) throws IOException {
        String sql = "select * from myMusic where id>" + id + " limit 1";
        cursor = db.rawQuery(sql, null);
        if(cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                Long id1 = cursor.getLong(cursor.getColumnIndex("id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String singer = cursor.getString(cursor.getColumnIndex("singer"));
                String songImgUrl = cursor.getString(cursor.getColumnIndex("songImgUrl"));
                String playUrl = cursor.getString(cursor.getColumnIndex("playUrl"));

                TextView textView = findViewById(R.id.play_song_name);
                MyImageView imageView = findViewById(R.id.play_song_img);

                textView.setText(name);
                imageView.setImageURL(songImgUrl);

                songDetail.setId(id1);
                songDetail.setName(name);
                songDetail.setSinger(singer);
                songDetail.setSongImgUrl(songImgUrl);
                songDetail.setPlayUrl(playUrl);

                initPerAndNext(id1);

                playMusic(playUrl);


            }
        }else {
            Toast.makeText(this,"后面没有歌曲啦",Toast.LENGTH_SHORT).show();
        }
    }

    // 播放前一首
    private void playPreSong(long id) throws IOException {
        String sql = "select * from myMusic where id<" + id + " order by id DESC limit 1 ";
        cursor = db.rawQuery(sql, null);
        if(cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {

                Long id1 = cursor.getLong(cursor.getColumnIndex("id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String singer = cursor.getString(cursor.getColumnIndex("singer"));
                String songImgUrl = cursor.getString(cursor.getColumnIndex("songImgUrl"));
                String playUrl = cursor.getString(cursor.getColumnIndex("playUrl"));

                TextView textView = findViewById(R.id.play_song_name);
                MyImageView imageView = findViewById(R.id.play_song_img);

                textView.setText(name);
                imageView.setImageURL(songImgUrl);

                songDetail.setId(id1);
                songDetail.setName(name);
                songDetail.setSinger(singer);
                songDetail.setSongImgUrl(songImgUrl);
                songDetail.setPlayUrl(playUrl);

                initPerAndNext(id1);

                playMusic(playUrl);
            }
        } else {
            Toast.makeText(this,"前面没有歌曲啦",Toast.LENGTH_SHORT).show();
        }
    }


    // 主要用来切歌的播放
    private void playMusic(String playUrl) {
        final String[] url = {playUrl};
        try {
            if (MediaPlayerServer.mediaPlayer == null) {
                MediaPlayerServer.mediaPlayer.setDataSource(playUrl);
                MediaPlayerServer.mediaPlayer.prepare();
                MediaPlayerServer.mediaPlayer.start();
                seekBar.setMax(MediaPlayerServer.mediaPlayer.getDuration());
                //获得歌曲现在播放位置并设置成播放进度条的值
                seekBar.setProgress(MediaPlayerServer.mediaPlayer.getCurrentPosition());
                handler.postDelayed(updateThread, 100);
            } else if (MediaPlayerServer.mediaPlayer.isPlaying()) {
                MediaPlayerServer.mediaPlayer.stop();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            MediaPlayerServer.mediaPlayer.reset();
                            MediaPlayerServer.mediaPlayer.setDataSource(playUrl);
                            MediaPlayerServer.mediaPlayer.prepare();
                            MediaPlayerServer.mediaPlayer.start();
                            seekBar.setMax(MediaPlayerServer.mediaPlayer.getDuration());
                            //获得歌曲现在播放位置并设置成播放进度条的值
                            seekBar.setProgress(MediaPlayerServer.mediaPlayer.getCurrentPosition());
                            handler.postDelayed(updateThread, 100);
                        } catch (Exception e) {
                            url[0] = "";
                            e.printStackTrace();
                        }
                    }
                }, 1000);

            } else {
                MediaPlayerServer.mediaPlayer.reset();
                MediaPlayerServer.mediaPlayer.setDataSource(playUrl);
                MediaPlayerServer.mediaPlayer.prepare();
                MediaPlayerServer.mediaPlayer.start();
                seekBar.setMax(MediaPlayerServer.mediaPlayer.getDuration());
                //获得歌曲现在播放位置并设置成播放进度条的值
                seekBar.setProgress(MediaPlayerServer.mediaPlayer.getCurrentPosition());
                handler.postDelayed(updateThread, 100);
            }
        } catch (Exception e) {
            url[0] = "";
        }
    }

}